package com.primaryedu.ui.app.growstep;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.SyncStateContract;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.bean.ClassDynamicBean;
import com.primaryedu.bean.MessagesBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.ui.BaseAppCompatActivity;
import com.primaryedu.ui.app.messageboard.MessagboarddetailsActivity;
import com.primaryedu.ui.app.messageboard.MessagesListAdapter;
import com.primaryedu.ui.app.nicedialog.BaseNiceDialog;
import com.primaryedu.ui.app.nicedialog.DialogCallBackUtils;
import com.primaryedu.ui.app.nicedialog.DialogSureCallBack;
import com.primaryedu.ui.app.nicedialog.MyCustomDialog;
import com.primaryedu.widget.PullToRefreshView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Thomas on 2018/1/25.
 */

public class ClassDynamicActiviy extends BaseAppCompatActivity implements View.OnClickListener, PullToRefreshView.OnHeaderRefreshListener,
        PullToRefreshView.OnFooterRefreshListener, ClassdynamicAdapter.DeleteCallback, DialogSureCallBack {
    private String TAG = ClassDynamicActiviy.class.getSimpleName();
    private ListView listView;
    private int page = 1;
    private final static int CLASSANDGRADE = 30; // "申请"返回的结果码
    private PullToRefreshView pullToRefreshView;
    private List<ClassDynamicBean.DataBean.ListBean> classdynamicLists = null;
    private List<ClassDynamicBean.DataBean.ListBean> classiddynamicLists = null;
    private boolean fistenter = true;
    private ClassdynamicAdapter classdynamicAdapter;
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != classDynamicBean.getData().getList() && classDynamicBean.getData().getList().size() != 0) {
                        if (classdynamicLists == null) {
                            classdynamicLists = classDynamicBean.getData().getList();

                            classdynamicAdapter = new ClassdynamicAdapter(ClassDynamicActiviy.this, classdynamicLists, ClassDynamicActiviy.this);
                            listView.setAdapter(classdynamicAdapter);

                        }else {
                            classdynamicLists.addAll(classDynamicBean.getData().getList());
                            classdynamicAdapter.notifyDataSetChanged();
                        }
                    }else {
                        if( classdynamicLists!=null && classdynamicLists.size()>0){
                            showToast( "亲，到底了");
                        }else{
                            showToast("亲，暂无数据");
                        }
                    }
                    break;
                case 1002:
                    if (null != classDynamicBean.getData().getList() && classDynamicBean.getData().getList().size() != 0) {
                        if (classiddynamicLists == null) {
                            classiddynamicLists = classDynamicBean.getData().getList();

                            classdynamicAdapter = new ClassdynamicAdapter(ClassDynamicActiviy.this, classiddynamicLists, ClassDynamicActiviy.this);
                            listView.setAdapter(classdynamicAdapter);

                        }else {
                            classiddynamicLists.addAll(classDynamicBean.getData().getList());
                            classdynamicAdapter.notifyDataSetChanged();
                        }
                    }else {
                        if( classiddynamicLists!=null && classiddynamicLists.size()>0){
                            showToast( "亲，到底了");
                        }else{
                            showToast("亲，暂无数据");
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };
    private ClassDynamicBean.DataBean.ListBean cd;
    private String className;
    private String classid = "";
    private int deletePosition;
    private ClassDynamicBean classDynamicBean;


    @Override
    protected int BindLayout() {
        return R.layout.activity_class_dynamic;
    }

    @Override
    protected void initView() {
        DialogCallBackUtils.setCallBack(this);
        ((TextView) findViewById(R.id.title)).setText("班级动态");
        findViewById(R.id.back).setOnClickListener(this);

        findViewById(R.id.right).setVisibility(View.VISIBLE);
        findViewById(R.id.right).setOnClickListener(this);
        ((TextView) findViewById(R.id.text_right)).setText("班级选择");
        ((TextView) findViewById(R.id.text_right)).setOnClickListener(this);
        ((TextView) findViewById(R.id.text_right)).setTextColor(getResources().getColor(R.color.main_button));

        listView = (ListView) this.findViewById(R.id.listView);


//        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
//                                    long arg3) {
//                VotelistBean.DataBean.ListBean vb = votetempList.get(position);
//                Intent intent = new Intent(VoteActivity.this,VoteDetailsActivity.class) ;
//                intent.putExtra("id",vb.getId());
//
//                startActivity(intent);
//            }
//        });
        pullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    @Override
    protected void initData() {
        getclassDynamic(fistenter);
    }

    private void getclassDynamic(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.classdynamicList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=masterboxlist=======" + response);

                        Gson gson = new Gson();
                        classDynamicBean = gson.fromJson(response, ClassDynamicBean.class);
                        if (classDynamicBean.getResult() == 1) {
                            handler.sendEmptyMessage(1001);

                        } else {
                            showToast("网络访问失败！");
                        }
                       /* try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                classdynamicLists = new Gson().fromJson(listStr,
                                        new TypeToken<List<ClassDynamicBean.DataBean.ListBean>>() {
                                        }.getType());
                                classdynamictempList.clear();
                                classdynamictempList.addAll(classdynamicLists);
                                handler.sendEmptyMessage(1001);

                                System.out.println("leaveLists==" + listStr);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }*/
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissLoading();
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                map.put("classId", GlobalData.getClassid(getApplicationContext()));
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    /**
     * 接口方法，响应ListView按钮点击事件
     */
    @Override
    public void deleteclick(View v) {
        Intent intent = null;
//        showToast("点击有效");
        switch (v.getId()) {
            case R.id.deleteBtn:
                deletePosition = (int) v.getTag(R.id.deleteBtn);
                cd = classdynamicLists.get(deletePosition);
                Log.i("yy", "deleteclick: =====" + cd.getId());
                MyCustomDialog.newInstance("deleteclassdynamic")
                        .setMargin(60)
                        .setOutCancel(false)
                        .show(getSupportFragmentManager());

                break;
            case R.id.headIv:
                int headIvPosition = (int) v.getTag(R.id.headIv);
                cd = classdynamicLists.get(headIvPosition);
                String userId = cd.getUserId();//点击头像的用户ID
                intent = new Intent(ClassDynamicActiviy.this, MyClassDynamicActivity.class);
                intent.putExtra("userId",userId);
                intent.putExtra("boolean","1");
                startActivity(intent);
                break;

        }

    }

    private void deleteClassdynamice(final ClassDynamicBean.DataBean.ListBean cd, final int deletePosition) {
        showLoading("删除中...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.deleteClassdynamic,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=voteuser=======" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                showToast("删除成功");
                                classdynamicLists.remove(deletePosition);
                                classdynamicAdapter.notifyDataSetChanged();
                            } else if (result == 0) {
                                showToast("删除失败，请重新删除！");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissLoading();
                errorLoading("删除失败，请重新删除！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("id", cd.getId());
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.text_right:
                intent = new Intent(ClassDynamicActiviy.this, GradeListActivity.class);
                startActivityForResult(intent, CLASSANDGRADE);
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择班级
                case CLASSANDGRADE:
                    className = data.getStringExtra("className");
                    classid = data.getStringExtra("calssId");
                    Log.i(TAG, "getParams:className== " + className);
                    Log.i(TAG, "getParams:classid== " + classid);
                    classiddynamicLists = null;
                    page = 1;
                    getclassidDynamic(true, classid);
                    break;
            }
        }
    }

    private void getclassidDynamic(boolean fistenter, final String classid) {
        if (fistenter) {
            showLoading("加载中...");
        }

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.classdynamicList,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("response=classidDynamic====" + response);
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            Gson gson = new Gson();
                            classDynamicBean = gson.fromJson(response, ClassDynamicBean.class);

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                if (listObj.getInt("count") == 0) {
                                    classdynamicLists.clear();
                                    showToast("暂无此年级动态");
                                } else {

                                    handler.sendEmptyMessage(1002);
                                   /* String listStr = listObj.getString("list");
                                    classiddynamicLists = new Gson().fromJson(listStr,
                                            new TypeToken<List<ClassDynamicBean.DataBean.ListBean>>() {
                                            }.getType());
                                    classdynamicLists.clear();
                                    classdynamictempList.addAll(classiddynamicLists);
                                    handler.sendEmptyMessage(1002);*/
                                }
                            }else {
                                showToast("网络访问失败！");
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                dismissLoading();
                errorLoading("访问失败，请重新刷新下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				map.put("status", "1");
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                map.put("classId", classid);
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }


    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                if (classid.equals("")) {
                    page++;
                    getclassDynamic(false);
                } else {
//                    requestmoreclassiddynamicList();
                    page++;
                    getclassidDynamic(false, classid);
                }
                pullToRefreshView.onFooterRefreshComplete();
            }
        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (classid.equals("")) {
                    page = 1;
                    classdynamicAdapter = null;
                    classdynamicLists = null;
                    getclassDynamic(false);
                } else {
                    page = 1;
                    classiddynamicLists = null;
                    getclassidDynamic(false, classid);
                }
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(ClassDynamicActiviy.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }
        }, 1500);
    }

    @Override
    protected void onResume() {
        super.onResume();
        DialogCallBackUtils.setCallBack(this);
        getclassDynamic(false);
    }

    @Override
    public void SureClick(String type, BaseNiceDialog dialog) {
        if ("deleteclassdynamic".equals(type)) {
            deleteClassdynamice(cd, deletePosition);
        }
        dialog.dismiss();
    }
}
